import { Message, Loading } from 'element-ui';
import { round, forEach, cloneDeep, map } from 'lodash-es';
import { saveAs } from 'file-saver';
import { useRequest } from '@/hooks/requestHooks.js';
import service from '@/utils/request.js';
import { blobValidate } from '@/utils/ruoyi';
import errorCode from '@/utils/errorCode';
import { printYear } from '@/utils/index.js';
import { getAllTypeLists } from '@/api/system/dict/data.js';

//重置表单
export const useResetForm = el => {
  if (el.value && isRef(el)) {
    el.value.clearValidate();
    el.value.resetFields();
  }
};
// 通用下载方法
export const useDownload = (url, params, filename) => {
  let downloadLoadingInstance;
  downloadLoadingInstance = Loading.service({
    text: '正在下载数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return service
    .post(url, params, {
      // transformRequest: [(params) => { return tansParams(params) }],
      // headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      headers: { 'Content-Type': 'application/json;charset=utf-8' },
      responseType: 'blob',
    })
    .then(async res => {
      const data = res.data;
      let serverFilename;
      const disposition = res.headers['content-disposition'];
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      const matches = filenameRegex.exec(disposition);
      if (matches != null && matches[1]) {
        serverFilename = decodeURI(matches[1].replace(/['"]/g, ''));
      }
      const isLogin = await blobValidate(data);
      if (isLogin) {
        const blob = new Blob([data]);
        saveAs(blob, serverFilename ? serverFilename : filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
        Message.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch(r => {
      Message.error('下载文件出现错误，请联系管理员！');
      downloadLoadingInstance.close();
    });
};

//根据文件url下载文件
export const useFileUrlDownload = (url, filename) => {
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      link.target = '_blank'; // 可选，如果希望在新窗口中下载文件，请取消注释此行
      link.click();
    });
};

//保留两位小数
export const useFormatCloud = () => {
  return function (value) {
    if (value === null || isNaN(value)) {
      return '--';
    } else {
      return round(value, 2);
    }
  };
};

//获取字典数据
export const useDictLists = dictTypes => {
  if (dictTypes.length > 0) {
    const [data] = useRequest(getAllTypeLists, {
      defaultParams: [dictTypes],
      cacheKey: 'JobType',
      cacheTime: 30 * 60 * 1000,
    });
    return data;
  }
};

//能耗数据转化
export const useHandleNhData = (original, result) => {
  let yearList = [];
  let yearList2 = [];
  forEach(original, n => {
    if (yearList.indexOf(n.startTime) === -1) {
      yearList.push(n.startTime);
    }
    if (yearList2.indexOf(n.endTime) === -1) {
      yearList2.push(n.endTime);
    }
  });
  const list = printYear(yearList[0], yearList2[yearList2.length - 1]);
  forEach(result, n => {
    forEach(list, yearItem => {
      const obj = {
        date: yearItem,
        basisType: '基准能耗',
      };
      const obj2 = {
        date: yearItem,
        basisType: '基准费用',
      };
      n.tableData.push(cloneDeep(obj), cloneDeep(obj2));
    });
  });
  forEach(original, n => {
    forEach(result, el => {
      // 1.取对应的楼栋
      if (el.buildingCode === n.buildingCode) {
        forEach(el.tableData, item => {
          if (item.date.substring(0, 4) === n.startTime.substring(0, 4)) {
            if (item.basisType === '基准能耗') {
              if (n.basisType === 'WATER') {
                item.WATER = n.basisQuantity;
              }
              if (n.basisType === 'ELECTRICITY') {
                item.ELECTRICITY = n.basisQuantity;
              }
              if (n.basisType === 'AIR') {
                item.AIR = n.basisQuantity;
              }
              if (n.basisType === 'WARM') {
                item.WARM = n.basisQuantity;
              }
            } else if (item.basisType === '基准费用') {
              if (n.basisType === 'WATER') {
                item.WATER = n.basisCost;
              }
              if (n.basisType === 'ELECTRICITY') {
                item.ELECTRICITY = n.basisCost;
              }
              if (n.basisType === 'AIR') {
                item.AIR = n.basisCost;
              }
              if (n.basisType === 'WARM') {
                item.WARM = n.basisCost;
              }
            }
          }
        });
      }
    });
  });
  return result;
};
